package com.mxchip.livestarmobile.mobile

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.duobeiyun.paassdk.bean.AVideoState
import com.duobeiyun.paassdk.bean.SolNetworkInformation
import com.duobeiyun.paassdk.media.DBIVideoCustomRender
import com.duobeiyun.paassdk.media.MediaType
import com.umeng.analytics.MobclickAgent
import com.mxchip.livestarmobile.mobile.av.screen.DecoderScreen
import com.mxchip.livestarmobile.mobile.base.HideSystemUILifecycleAware
import com.mxchip.livestarmobile.mobile.repository.RoomClientRepository
import com.mxchip.livestarmobile.mobile.state.SystemData
import com.mxchip.livestarmobile.mobile.ui.Call
import com.mxchip.livestarmobile.mobile.ui.call.*
import com.mxchip.livestarmobile.mobile.util.Camera.CameraHandle
import com.mxchip.livestarmobile.mobile.util.Log.FileLog
import com.mxchip.livestarmobile.mobile.util.Log.MyLog
import com.mxchip.livestarmobile.mobile.util.NetMap
import com.mxchip.livestarmobile.mobile.util.SendAudioUtil
import com.mxchip.livestarmobile.mobile.util.Utils
import com.mxchip.livestarmobile.mobile.util.network.NetSpeed
import com.mxchip.livestarmobile.mobile.util.network.NetSpeedTimer
import com.mxchip.livestarmobile.mobile.base.toast
import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.duobeiyun.CustomAudioSource
import com.mxchip.livestarmobile.mobile.duobeiyun.CustomVideoSource
import com.mxchip.livestarmobile.mobile.repository.DbyEngineRepository
import com.mxchip.livestarmobile.mobile.repository.SDKEventListenerWrap
import com.mxchip.livestarmobile.mobile.state.AppConstant
import com.videohigh.hxb.roomclient.AbsMeetingSocketCallback
import com.videohigh.hxb.roomclient.event.InvitationEvent
import com.videohigh.hxb.roomclient.event.VideoDeviceAddEvent
import com.videohigh.hxb.roomclient.event.VideoDeviceRemoveEvent
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_call_a.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean

class CallActivityA : AppCompatActivity(), Handler.Callback {

    private lateinit var navController: NavController
    private lateinit var appBarConfiguration: AppBarConfiguration

    private val logger = FileLog.getLogger(CallActivityA::class.java)
    private val dbyViewModel by viewModels<DbyViewModel>()

    private val screenViewModel by viewModels<ScreenViewModel>()
    private val dbyNetworkViewModel by viewModels<DbyNetworkViewModel>()
    private val roomViewModel by viewModels<RoomViewModel>()


    private val handler: Handler by lazy {
        Handler(this)
    }
    private var mNetSpeedTimer: NetSpeedTimer? = null


    private var customVideoSource: CustomVideoSource? = CustomVideoSource()
    private var customAudioSource: CustomAudioSource? = CustomAudioSource()
    private var checkBadNetWork = 0

    val realUserId = "${SystemData.roomId()}T${SystemData.userId()}"
    private val callback: AbsMeetingSocketCallback = object : AbsMeetingSocketCallback() {

        override fun onVideoDeviceAdd(event: VideoDeviceAddEvent) {

            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +
                    "CallActivityA::onVideoDeviceOpen: roomViewModel.videoDevices:${event}")
            Log.e("CallActivityA", "onVideoDeviceAdd $event")

            lifecycleScope.launch {
                val fromTermNumber = "${event.from.roomId}T${event.from.termId}"
                event.deviceNames.forEach { deviceName ->
                    roomViewModel.addAVDevice(AVDevice(fromTermNumber, deviceName))
                }
            }
        }

        override fun onVideoDeviceRemove(event: VideoDeviceRemoveEvent) {

            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +
                    "CallActivityA::onVideoDeviceOpen: roomViewModel.videoDevices:${event}")
            Log.e("CallActivityA", "onVideoDeviceRemove $event")

            lifecycleScope.launch {
                val fromTermNumber = "${event.from.roomId}T${event.from.termId}"

                event.deviceNames.forEach { deviceName ->
                    roomViewModel.removeAVDevice(fromTermNumber, deviceName)
                }
            }

        }
    }

    private val mDbyEngine: DbyEngineRepository by lazy {
        DbyEngineRepository.init(applicationContext, AppConstant.DBY_PASS_APPID, AppConstant.DBY_PASS_APPKEY)
        customVideoSource?.let { DbyEngineRepository.setDBVideoSource(it) }
        customAudioSource?.let { DbyEngineRepository.setDBAudioSource(it, false) }
        DbyEngineRepository.setSDKEventListener(dbyEventHandler)
        DbyEngineRepository
    }

    /*private val mDbyEngine: DbyEngine by lazy {
        DbyEngine.createInstance(applicationContext, AppConstant.DBY_PASS_APPKEY, AppConstant.DBY_PASS_APPID, dbyEventHandler).also {
            it.setDBVideoSource(customVideoSource)
            it.setDBAudioSource(customAudioSource, false)
        }
    }*/

    private val dbyEventHandler = object : SDKEventListenerWrap() {
        var netDescrib: StringBuilder = StringBuilder()
        var oldTime: Long = 0
        var SolNetworkInformationIndex = 0
        var currentLevel = SystemData.networkLevelStandard
        override fun onJoinChannelSuccess(channel: String, userId: String, userName: String) {
            super.onJoinChannelSuccess(channel, userId, userName)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onJoinChannelSuccess $channel $userId")
            lifecycleScope.launch {
                dbyViewModel.userAdd(userId)
                // dbyViewModel.camera(true)
            }
        }

        /*override fun onRejoinChannelSuccess(channel: String, userId: String, userName: String) {
            super.onRejoinChannelSuccess(channel, userId, userName)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onRejoinChannelSuccess channel:$channel userID:$userId")
        }*/

        override fun onUserJoined(uid: String, userName: String) {
            super.onUserJoined(uid, userName)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onUserJoined $uid")
            lifecycleScope.launch {
                dbyViewModel.userAdd(uid)
            }
            setCustomRemoteRender(uid, AVDevice.CAMERA_LOCAL)
            setCustomRemoteRender(uid, AVDevice.CAMERA_LOCAL_SMALL)
            setCustomRemoteRender(uid, AVDevice.CAMERA_HDMI)
            setCustomRemoteRender(uid, AVDevice.CAMERA_WIFI)

        }


        /*override fun onRemoteVideoStateChanged(userId: String, deviceName: String, state: AVideoState) {
            super.onRemoteVideoStateChanged(userId, deviceName, state)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onRemoteVideoStateChanged userId:$userId, deviceName:$deviceName, state:$state")
            // if (state == AVideoState.INIT) {
            // dbyViewModel.videoAdd(userId)
            // }
            // if (state == AVideoState.STOP) {
            // dbyViewModel.videoRemove(userId)
            // }
        }*/

        /*override fun onError(errcode: Int) {
            super.onError(errcode)
            logger.error(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onError $errcode")
        }*/


        override fun onLeaveChannel() {
            super.onLeaveChannel()
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onLeaveChannel ")
            mDbyEngine.destroy()
            finish()
        }

        override fun onUserLeave(uid: String) {
            super.onUserLeave(uid)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onUserLeave $uid")
            lifecycleScope.launch {
                dbyViewModel.userRemove(uid)
            }
        }

        override fun onRemoteMicStateChange(uid: String, deviceName: String, state: AVideoState) {
            super.onRemoteMicStateChange(uid, deviceName, state)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onRemoteMicStateChange uid:$uid devicesName:$deviceName state:$state\"")
            if (!dbyViewModel.mIsEnter.value!!) {
                logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + "CallActivityA::onRemoteMicStateChange muteRemoteAudioStream true:${uid}_$deviceName")
                val result = mDbyEngine.muteRemoteAudioStream(uid, deviceName, true)
                mDbyEngine.muteRemoteAudioStream(uid, "", true)
            }

            lifecycleScope.launch {
                if (state == AVideoState.INIT) {
                    dbyViewModel.audioAdd(uid)
                } else if (state == AVideoState.STOP) {
                    dbyViewModel.audioRemove(uid)
                }
            }

        }

        /*override fun onConnectionStateChanged(code: Int) {
            super.onConnectionStateChanged(code)
            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onConnectionStateChanged $code")
        }*/

        override fun onNetworkQuality(userId: String, txQuality: Int, rxQuality: Int) {
            super.onNetworkQuality(userId, txQuality, rxQuality)
//            Log.e("CallActivity", "onNetworkQuality:id:$userId txQuality:${NetMap.getTxQuality(txQuality)} rxQuality:=${NetMap.getRxQuality(rxQuality)}")
            if (System.currentTimeMillis() - oldTime < 200) {
                netDescrib.append("id:$userId\ntxQuality↑:${NetMap.getTxQuality(txQuality)}\nrxQuality↓:${NetMap.getRxQuality(rxQuality)}\n")
            } else {
                netDescrib.clear()
                netDescrib.append("id:$userId\ntxQuality↑:${NetMap.getTxQuality(txQuality)}\nrxQuality↓:${NetMap.getRxQuality(rxQuality)}\n")
            }
            oldTime = System.currentTimeMillis()
            dbyViewModel.netQuality(netDescrib.toString())


            if (userId == SystemData.userId()) {
                lifecycleScope.launch {
                    dbyNetworkViewModel.setTxQuality(txQuality)
                    dbyNetworkViewModel.setRxQuality(rxQuality)
                }
                if ((txQuality in 5..6 || rxQuality in 5..6) && readyFinish.get()) {
                    modifyFinish.set(false)
                    while (badNetwork.size >= 5) {
                        badNetwork.pollLast()
                    }
                    badNetwork.push(BadNetwokData())
                    modifyFinish.set(true)
                }
            }

//            logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date())+
//                    "CallActivityA::onNetworkQuality ")
        }

        override fun onNetWorkDelay(delay: Int) {
            super.onNetWorkDelay(delay)
            Log.d("CallActivity", "network-----onNetWorkDelay: $delay")

            lifecycleScope.launch {
                dbyNetworkViewModel.setDelay(delay)
            }

        }

        override fun onSolNetworkInformation(information: SolNetworkInformation?) {
            if (information == null) return
            SolNetworkInformationIndex += 1 % 100;
//            Log.d("CallActivityA::SolNetworkInformation", "information:$information")
            if (SolNetworkInformationIndex < 7) {
                logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date())
                        + "SolNetworkInformation:$information")
            }
            if (information.isVideoStream && information.userId == realUserId && information.deviceName != AVDevice.AUDIO_BUILD_IN) {
//                Log.d("CallActivityA::SolNetworkInformation", "information:$information")
                Log.d("CallActivityA::SolNetworkInformation:Self",
                        "deviceName:${information.deviceName} bwadv:${information.bwadv} bwcur:${information.bwcur} lostRate:${information.lostRate} ")
                if (information.bwadv == 0 && information.lostRate == 0.0f) return

                if (information.bwadv < SystemData.lowerBitRate || information.lostRate > 0.3) {
                    currentLevel = SystemData.networkLevelMinimum

                } else if (information.bwadv < SystemData.middleBitRate || information.lostRate > 0.2) {
                    currentLevel = SystemData.networkLevelLower

                } else if (information.bwadv < SystemData.standardBitRate || information.lostRate > 0.1) {
                    currentLevel = SystemData.networkLevelMiddle

                } else if (information.bwadv > SystemData.standardBitRate || information.lostRate < 0.1) {
                    currentLevel = SystemData.networkLevelStandard

                }
                if (currentLevel != screenViewModel.networkLevel.value!!)
                    screenViewModel.networkLevel(currentLevel)
            }


        }
        override fun onMgtMuteAudioEvent() {
            Log.e("CallActivityA", "onMgtMuteAudioEvent ${Thread.currentThread()}")
            dbyViewModel.mic(false)

            lifecycleScope.launch {
                toast("收到会控消息，正在静音")
            }
        }

        override fun onMgtMuteCameraEvent() {
            Log.e("CallActivityA", "onMgtMuteCameraEvent ${Thread.currentThread()}")
            dbyViewModel.camera(false)

            lifecycleScope.launch {
                toast("收到会控消息，正在关闭关闭摄像头")
            }
        }

        override fun onMgtMuteShareContentEvent() {

        }
    }
    val muteAll = arrayListOf<String>()
    private fun setCustomRemoteRender(uid: String, deviceName: String) {
        mDbyEngine.setRemoteVideoCustomRenderer(uid, deviceName, object : DBIVideoCustomRender {

            override fun videoRenderInit(deviceName: String) {
                logger.info("CallActivityA::videoRenderInit::uid${uid} deviceName:${deviceName}  ")

                logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::videoRenderInit dbyViewModel.streamingAVDevices.value ${screenViewModel.streamingAVDevices.value}")

                val devices = screenViewModel.streamingAVDevices.value?.filter {
                    it.uid == uid && it.deviceName == deviceName
                }


                if ((devices == null || devices.isEmpty()) && deviceName != AVDevice.CAMERA_HDMI && deviceName != AVDevice.CAMERA_WIFI) {

                    val result = mDbyEngine.muteRemoteVideoStream(uid, deviceName, true)
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::videoRenderInit muteRemoteVideoStream true: device:$deviceName uid:$uid $devices")
                } else {
                    val result = mDbyEngine.muteRemoteVideoStream(uid, deviceName, false)
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::videoRenderInit muteRemoteVideoStream false: device:$deviceName uid:$uid $devices")
                }

                lifecycleScope.launch {
                    val avDevice = AVDevice(uid, deviceName)
                    dbyViewModel.addAVDevice(avDevice)
                }

            }

            override fun videoRenderDestroy(deviceName: String) {
                //销毁对应的播放器
                logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivity::videoRenderDestroy: deviceName:$deviceName uid:$uid")

                lifecycleScope.launch {
                    dbyViewModel.removeAVDevice(uid, deviceName)
                }

                if (deviceName == "hdmi") {
                    muteAll.clear()
                }

            }

            override fun getDBMediaFrameType(deviceName: String): Int {
                return MediaType.DBMediaFrameType.H264.type
            }

            override fun getDBMediaBufferType(deviceName: String): Int {
                //如果是264数据；只会传递 byte[]的数据类型
                return MediaType.DBMediaBufferType.BYTE_ARRAY.type
            }

            override fun customByteArrayFrame(deviceName: String, data: ByteArray, format: Int, width: Int, height: Int, rotation: Int, timestamp: Long) {

//                 Log.e("ygscustomByteaarray", "customByteArrayFrame: " + deviceName + " data.length=" + data.size + "   uid:" + uid)
                if (!muteAll.contains("${uid}_$deviceName")) {
                    muteAll.add("${uid}_$deviceName")
                    Log.e("CallActivityA", "customByteArrayFrame muteRemoteVideoStream true: uid_deviceName: ${uid}_$deviceName data.size:${data.size} data:$data data:${Arrays.toString(data)} ")

                }
                val avPacket = AVPacket(data, deviceName, uid, format, width, height, rotation, timestamp)
                if (deviceName == AVDevice.CAMERA_HDMI) {
//    FIleManager.write(data)
                }
                // Log.e("CallActivity", "receiveAVPacket: ${avPacket.uid}_${avPacket.deviceName}")

                dbyViewModel.receiveAVPacket(avPacket)
            }

            override fun customByteArrayFrame(deviceName: String?, data: ByteArray?, format: Int, width: Int, height: Int, expectWidth: Int, expectHeight: Int, rotation: Int, timestamp: Long) {
                //  empty impl
            }

            override fun customByteBufferFrame(deviceName: String, buffers: ByteBuffer, format: Int, w: Int, h: Int, timestamp: Int) {
                // emtpy impl
            }

        })

    }

    private fun stopNetSpeedTimer() {
        handler.removeCallbacksAndMessages(null)
        mNetSpeedTimer?.stopSpeedTimer()
        mNetSpeedTimer = null
    }

    override fun onDestroy() {
        super.onDestroy()
        stopNetSpeedTimer()

        RoomClientRepository.removeCallbackHandler(callback)

        MyLog.logD(MyLog.CALL_ACTIVITY_A_MODEL, "CallActivityA::onDestroy ")
    }

    var modifyFinish = AtomicBoolean(true)
    var readyFinish = AtomicBoolean(true)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_call_a)

        lifecycle.addObserver(HideSystemUILifecycleAware())

        setSupportActionBar(toolbar)

        appBarConfiguration = AppBarConfiguration.Builder()
                .setFallbackOnNavigateUpListener {
                    finish()
                    true
                }
                .build()

        navController = Navigation.findNavController(this, R.id.nav_host_fragment)

        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)

        supportActionBar?.hide()

        /*if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container, VideoFragment())
                    .commitNow()
        }*/


        RoomClientRepository.addCallbackHandler(callback)


        //创建NetSpeedTimer实例
        mNetSpeedTimer = NetSpeedTimer(this, NetSpeed(), handler).setDelayTime(500).setPeriodTime(500)
        //在想要开始执行的地方调用该段代码
        mNetSpeedTimer?.startSpeedTimer()

        dbyViewModel.join().observe(this, Observer { roomId ->
            Log.e("CallActivity", "roomId: $roomId")

            if (roomId == null) {
                logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onCreate destroy $roomId")

                SendAudioUtil.getInstance().clear()
                //SystemData.getInstance().streamMode = StreamMode.SINGLE
                CameraHandle.getInstance().stopCamera()
                customVideoSource = null
                customAudioSource = null
                mDbyEngine.leaveChannel()
            } else {
//                FIleManager.create()
                mDbyEngine.joinChannel(roomId, realUserId, realUserId)
                mDbyEngine.recovery()
            }
        })


        dbyViewModel.sendAVPacketConsumer(Consumer { avPacket ->
//            MyLog.logD("CallActivityA::onCreate deviceName1:${avPacket.deviceName}")
            customVideoSource?.frameCustomMap?.get(avPacket.deviceName)?.let {
                // Log.e("CallActivity", "sendAVPacket: " + avPacket.data.size)
                avPacket.apply {
                    MyLog.logD(MyLog.CALL_ACTIVITY_A_MODEL, "CallActivityA::sendAVPacketConsumer deviceName:$deviceName avPacket:${this.uid}_${this.deviceName}")
                    it.customByteArrayFrame(deviceName, data, format, width, height, if (Utils.checkIsIFrame(data)) 0 else 1, System.currentTimeMillis())
                }
            }
        })

        SendAudioUtil.getInstance().setGetAudioData(object : SendAudioUtil.GetAudioData {
            override fun getAudioData(avPacket: AVPacket) {
                MyLog.logD(MyLog.SEND_AUDIO_PACKET_MODEL,"CallActivityA: getAudioData:  customAudioSource?.frameCustomMap----- avPacket.deviceName:${avPacket.deviceName} data.size:${avPacket.data.size}")
                customAudioSource?.frameCustomMap?.get(avPacket.deviceName)?.let {
                    avPacket.apply {
//                        if (RoomClientRepository.state.value != RoomClientRepository.State.BUSY) return@apply
//                        FIleManager.writeOther(data)
                        MyLog.logD(MyLog.SEND_AUDIO_PACKET_MODEL,"CallActivityA: getAudioData:  customByteArrayFrame----- deviceName:$deviceName data.size:${data.size}")
                        it.customByteArrayFrame(deviceName, data, data.size, 0)
                    }
                }
            }

        })
        dbyViewModel.camera.observe(this, Observer { enable ->
            val r0 = mDbyEngine.enableLocalCamera(AVDevice.CAMERA_LOCAL, enable)
            val r1 = mDbyEngine.enableLocalCamera(AVDevice.CAMERA_LOCAL_SMALL, enable)

            screenViewModel.frontCameraPreview(enable)
            if (enable) {
                var num = 3;
                lifecycleScope.launch {
                    while (num-- > 0) {
                        CameraHandle.getInstance().applyIFrame()
                        delay(1000)
                    }
                }

            }
            Log.e("CallActivity", "CAMERA_LOCAL result: $r0 $r1")
        })

        dbyViewModel.mic.observe(this, Observer { enable ->
            val result = mDbyEngine.enableLocalAudio(AVDevice.AUDIO_BUILD_IN, enable)
            Log.e("CallActivity", "mic result: $result enable:$enable")
        })

        dbyViewModel.audioList.observe(this, Observer { audioList ->
            audioList?.map {
                //TODO:1.开启远端音频流每次操作的都是一组数据,应当只操作对应变化的数据 2.应该收到AVideoState.STOP调用关闭音频设备
                logger.info("CallActivityA::onCreate audioList:muteRemoteAudioStream false:${it}_${AVDevice.AUDIO_BUILD_IN}")
                mDbyEngine.muteRemoteAudioStream(it, AVDevice.AUDIO_BUILD_IN, false)
                mDbyEngine.muteRemoteAudioStream(it, "", false)
            }
        })

        roomViewModel.avDevices.observe(this, Observer {
            screenViewModel.setAVDevices(it)
        })

        screenViewModel.screenSettings.observe(this, Observer {

            val streamingAVDevices = screenViewModel.streamingAVDevices.value?.toList()

            val nextOnScreenAVDevices = it?.allScreens?.filterIsInstance<DecoderScreen>()?.map { screen ->
                AVDevice(screen.deviceUid, screen.deviceName)
            }

            streamingAVDevices?.forEach { avDevice ->
                if ((nextOnScreenAVDevices == null || !nextOnScreenAVDevices.contains(avDevice))) {
                    if (avDevice.deviceName != AVDevice.CAMERA_HDMI && avDevice.deviceName != AVDevice.CAMERA_WIFI) {
                        val result = mDbyEngine.muteRemoteVideoStream(avDevice.uid, avDevice.deviceName, true)
                        Log.e("CallActivityA", "muteRemoteVideoStream true: result $result avDevice:${avDevice.uid}_${avDevice.deviceName}")
                    }
                    screenViewModel.removeStreamingAVDevice(avDevice.uid, avDevice.deviceName)
                }
            }

            nextOnScreenAVDevices?.forEach { avDevice ->
                if (avDevice.deviceName != AVDevice.CAMERA_HDMI && avDevice.deviceName != AVDevice.CAMERA_WIFI) {
                    val result = mDbyEngine.muteRemoteVideoStream(avDevice.uid, avDevice.deviceName, false)
                    Log.e("CallActivityA", "muteRemoteVideoStream false: result $result avDevice:${avDevice.uid}_${avDevice.deviceName}")
                }
                screenViewModel.addStreamingAVDevice(avDevice)
            }

        })


        mDbyEngine.setDefaultAudioRoutetoSpeakerphone(true)

        lifecycleScope.launch {
            while (true) {
                readyFinish.set(false)
                while (!modifyFinish.get()) {
                    delay(100)
                }
                val array = badNetwork.filter {

                    val delta = System.currentTimeMillis() - it.time

                    val b = (delta < 11 * 1000)

                    Log.e("CallActivityA", "badNetwork: $it, delta: $delta")

                    b
                }
                readyFinish.set(true)
                if (array.size >= 4) {
                    checkBadNetWork++
                    if (checkBadNetWork >= 12) {
                        logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + " CallActivityA::onCreate badNetwork AutoHangup-----多贝挂断")
//                        toast("当前网络状况差，通话即将结束~~~")
//                        dbyViewModel.join(null)
//                        RoomClientRepository.hangup()
                    } else {
                        toast("当前通话质量不佳~~~")
                    }

                } else {
                    checkBadNetWork = 0
                }
                muteAll.clear()
                delay(10 * 1000)
            }
        }
    }


    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this) // 不能遗漏
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this) // 不能遗漏
    }

    override fun onStop() {
        super.onStop()


    }


    override fun handleMessage(msg: Message?): Boolean {
        if (msg!!.what == NetSpeedTimer.NET_SPEED_TIMER_DEFAULT) {
            val speed = msg.obj as String
            lifecycleScope.launch {
                dbyNetworkViewModel.setSpeed(speed)
            }
        }
        return false
    }

    override fun onSupportNavigateUp(): Boolean { // Allows NavigationUI to support proper up navigation or the drawer layout
        // drawer menu, depending on the situation.
        return NavigationUI.navigateUp(navController, appBarConfiguration)
    }

    companion object {

        fun open(context: Context, call: Call) {
            if (!RoomClientRepository.connected()) return
            val intent = Intent(context, CallActivityA::class.java)
            intent.putExtra(CallConst.CALL_POJO, call)
            context.startActivity(intent)
        }

        fun open(context: Context, event: InvitationEvent) {
            val intent = Intent(context, CallActivityA::class.java)
            intent.putExtra(CallConst.NOTIFY_INFO, event)
            context.startActivity(intent)
        }
    }

    val badNetwork = LinkedList<BadNetwokData>()

    data class BadNetwokData(val time: Long = System.currentTimeMillis())

    override fun onBackPressed() {
        return
    }


}
